package engine.scheduler.jobs.impl.quartz;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;

import engine.Consts;
import engine.dataobjects.MailItemInstance;
import engine.scheduler.jobs.IMailItemJob;
import engine.scheduler.jobs.IMailItemJobDetail;


public class MailItemJob implements IMailItemJob {

	private static Log log = LogFactory.getLog(MailItemJob.class);
	
	/**********
	 * I N J E C T I O N
	 **********/

	@Autowired
	Scheduler scheduler;

	Trigger defaultTrigger;
	

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}


	public void setDefaultTrigger(Trigger defaultTrigger) {
		this.defaultTrigger = defaultTrigger;
	}

	
    /* (non-Javadoc)
	 * @see engine.scheduler.jobs.IMailItemJob#init(engine.dataobjects.Mailitem, boolean)
	 */
    @Override
	public void init(IMailItemJobDetail jobDetails, boolean isNow) {
		MailItemInstance item = jobDetails.getItem();
    	try {
    		String interval = item.getJobInterval();
    		Trigger trigger = null;
    		if (isNow) {
    			log.debug(item.getItem().getName() + ": adding simple trigger to run now");
    			trigger = new SimpleTrigger(MailItemJobDetail.getNameForItem(item), Consts.MESSAGE_JOB_GROUP);
    		} else {				
    			if (interval == null || interval.length() == 0) {
    				log.debug(item.getItem().getName() + ": adding default trigger");
    				trigger = defaultTrigger;
    				trigger.setGroup(Consts.MESSAGE_JOB_GROUP);
    				trigger.setName(MailItemJobDetail.getNameForItem(item));
    			} else {
    				interval = item.getJobInterval();
    				trigger = new CronTrigger(MailItemJobDetail.getNameForItem(item), Consts.MESSAGE_JOB_GROUP, interval);		
    				log.debug(item.getItem().getName() + ": adding cron trigger");
    			}
    		}
    		// creating our job and adding it to the scheduler
     		jobDetails.setJobClass(this.getClass());
     		scheduler.scheduleJob(jobDetails.getJobDetail(), trigger);
     		log.info("============== start adding item ===================");
     		log.info("added item: " + item.toString());
    		log.info("added job ("+MailItemJobDetail.getNameForItem(item)+") details: " + jobDetails.getJobDetail().getFullName());
    		log.info("added trigger ("+trigger.getName()+"): next run at: " + trigger.getNextFireTime());
     		log.info("============== done adding item ===================");
			
		} catch (Exception e) {
			log.error("Could not start: " + item.toString());
			log.error(item.getItem().getName(), e);
		}
	
    }
    

    
    /* (non-Javadoc)
	 * @see engine.scheduler.jobs.IMailItemJob#execute(mailer.dataobjects.MailItem)
	 */
    @Override
	public void execute(IMailItemJobDetail jobDetails) throws Exception{
    	MailItemInstance item = jobDetails.getItem();
		// sending the message
		jobDetails.getMailService().mail(item);
    }
    	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try {
			log.debug("executing " + arg0.getJobDetail().toString());
	
			// getting our mail item from the context
			IMailItemJobDetail  item = (IMailItemJobDetail)arg0.getJobDetail();
			execute(item);
			
			// some additional log info.
			log.debug("done executing " + arg0.getJobDetail().toString());
			
			log.info("next run is at: " + arg0.getNextFireTime() + " for " + arg0.getJobDetail().toString());							
		} catch (Exception e) {
			log.error("Could execute scheduled task." , e);
		}
	}
	

}
